# -*- coding: utf-8 -*-
import urllib2, cookielib, urllib
import re
import time
from var import *
import var

illchar=('?','╲','*', '\\',',','"','<','>','|','“','"','，','‘','”',',','/',':')

cookiejar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
opener.addheaders = [("User-Agent","Mozilla/4.0 (compatible; MSIE 7.1; Windows NT 5.1; SV1)"),]
urllib2.install_opener(opener)

task_types = {'a':'searchjzfirst.do','b':'searchallfirst.do','important':'searchcfirst.do',}
        
class Article(object):
    def __init__(self,id,title):
        self.id = id
        self.name = title
        self.dblink = []
        self.dbtype = []
        self.download_time = 0
        self.download_sizes = []
        self.filepath = ''
        self.exclude_db = []
        self.retry_db = ''
    
def login():
    inputcode = ""
    r = urllib2.Request(login_url, urllib.urlencode({
        'username':username,'password':password,
        'Submit':'%E7%99%BB%E5%BD%95',
        'inputCode':''}))
    urllib2.urlopen(r).read()
#    response = opener.open(login_url,urllib.urlencode({
#        'username':username,'password':password,
#        'Submit':'%E7%99%BB%E5%BD%95',
#        'inputCode':''})).read()
    
#锁定任务
def lock_task(id):
    try:
        opener.open("http://www.firstdrs.com/admin/first/searchnosend.do?confine=&id="+id+"&add=sdjz")
    except Exception:
        pass
    #print "lock task " + id

#添加任务
def add_task(id,task_type):
    task_url = "http://www.firstdrs.com/admin/" + task_types[task_type]
    try:
        opener.open(task_url+'?id='+id+"&add=add&pages=1&sel=&taxis=&sw=")
        with lock:
            print "add task " + id
    except Exception:
        pass
    
#删除任务    
def del_task(id):
    try:
        opener.open("http://www.firstdrs.com/admin/first/searchnosend.do?confine=&id="+id+"&add=del")
    except Exception:
        pass
    with lock:
        print "delete task " + id

def get_html(url):
    try:
        return opener.open(url).read()
    except Exception, e:
        return 0

    
def check_valid(task):
    """
    检查该ID是有含有有效链接，如果有效构建Article对象放入下载队列中
    """
    # article_url为当前ID发送页面的链接
    task_id = task
    article_url = "http://www.firstdrs.com/admin/first/quicksend.do?id=" + task_id
    try:
        send_html = opener.open(article_url).read()
    except Exception, e:
        return -1
    if 'saveCode.png' in send_html:
        return -2
    # 从发送页面提取读秀链接
    duxiu_url = re.findall(r"requestMag\('lmagmount', '(.*?)'\);",send_html)
    if not duxiu_url:
        return 0
    try:
        duxiu_html = opener.open(duxiu_url[0]).read()
    except Exception,e:
        return -1
    dblinks = re.findall(r"<a href='(.*?)' target='_blank'>",duxiu_html) #提取数据库链接
    #在提取数据库连接的时候，几次返回的数据可能不一样！！
    if not dblinks:
        return 0
    try:
        title = re.findall(r'<input id="title" type="hidden" value="(.*?)"/',send_html)[0]
        title = resharp(title)
    except Exception,e:
        title = str(task_id)
    article = Article(task_id,title)
    for dblink in dblinks:
        d = re.search('type=(\d+)',dblink).groups()[0]
        if d in var.normal_dbs:
            article.dblink.append(dblink)
    if article.dblink:
        if var.auto_download:
            var.download_queue.put(article)
        return 1
    return 0

def get_salary():
    t = time.localtime()
    year,month,day = t.tm_year,t.tm_mon,t.tm_mday
    today_url = "http://www.firstdrs.com/admin/stat/sz/typestatcountuser.do"
    month_url = "http://www.firstdrs.com/admin/stat/sz/typestatcountuser.do?stattype=&stime=%s-%s-%s&etime=%s-%s-%s&px=1" % (year,str(month).zfill(2),'01',
                                                                                                                             year,str(month).zfill(2),
                                                                                                                             str(day).zfill(2))
    html = opener.open(month_url).read()
    counts = re.findall("<td align = \"center\">(\d+)</td",html)[-13:]
    total = counts[-1]
    types = ['中文期刊','外文期刊','报纸','中文学位论文','外文学位论文',
             '中文会议论文','外文会议论文','中文专利','外文专利','中文标准',
             '外文标准','提问','合计']
    for i in range(len(types)):
        print types[i].decode('UTF-8').encode('gbk') + ' ' + counts[i]
    salary_today = 0.3*float(counts[-1])+0.2*(float(counts[3])+float(counts[1]))
    print '您这个月的薪水至少为 %s 元'.decode('UTF-8').encode('gbk') % salary_today

def resharp(title):
    for c in illchar:
        title=title.replace(c,"-")
    # 字符串编码问题
    try:
        title = title.decode('UTF-8').encode('gbk')
    except Exception, e:
        pass
    return title
